﻿/******************************************************************* 
* Copyright (C)  版权所有
* 创建时间:2019/4/26 8:32:58
* 作    者: zhenhua.shen
* 邮    箱：1025556487@qq.com
* 描    述：类功能描述
* 修改记录:修改类的记录
* 修改人:修改此类的人名称
* 版 本 号:v1.0.0
**********************************************************************/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ECharts.Designer;
using ECharts.Utility;
using ECharts.Title;
using ECharts.Tooltip;
using ECharts.Legend;
using ECharts.Axis;
using ECharts.Series;
using ECharts.ToolBox;
using Newtonsoft.Json.Converters;
using System.Collections;

namespace ECharts
{
    [Designer(typeof(ChartDesigner))]
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:EChart  runat=server></{0}:EChart>")]
    public class EChart : WebControl
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null)? "[" + this.ID + "]" : s);
            }
 
            set
            {
                ViewState["Text"] = value;
            }
        }

        
        public override  Unit Height
        {
            get
            {
                if (base.Height == Unit.Empty)
                {
                    return 100;
                }
                return base.Height;
            }
            set
            {
                base.Height = value;
            }
        }

        
        
        public override Unit Width
        {
            get
            {
                if (base.Width == Unit.Empty)
                {
                    return 100;
                }
                return base.Width;
            }
            set
            {
                base.Width = value;
            }
        }



        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }


        #region 旧代码
        //private Title.Title _title = new Title.Title();
        //public Title.Title Title2
        //{
        //    get
        //    {
        //        return _title;
        //    }
        //    set
        //    {
        //        _title = value;
        //    }
        //}
       
       //[Description("子标题")]
       // public string SubTitle
       // {
       //     get
       //     {
       //         return (string)ViewState["SubTitle"];
       //     }
       //     set
       //     {
       //         ViewState["SubTitle"] = value;
       //     }
       // }

       //[Category("工具栏")]
       //[Description("是否显示工具栏")]
       //public bool ShowToolbox
       //{
       //    get
       //    {
       //        if(ViewState["ShowToolbox"]==null)
       //        {
       //            return true;
       //        }
       //        return (bool)ViewState["ShowToolbox"];
       //    }
       //    set
       //    {
       //        ViewState["ShowToolbox"] = value;
       //    }
       //}

       //[Category("工具栏")]
       //[Description("是否在工具栏显示另存为图片按钮")]
       //public bool ShowSaveAsImageButton
       //{
       //    get
       //    {
       //        if (ViewState["ShowSaveAsImageButton"] == null)
       //        {
       //            return true;
       //        }
       //        return (bool)ViewState["ShowSaveAsImageButton"];
       //    }
       //    set
       //    {
       //        ViewState["ShowSaveAsImageButton"] = value;
       //    }
       //}

       //[Category("工具栏")]
       //[Description("是否在工具栏显示还原按钮")]
       //public bool ShowRestoreButton
       //{
       //    get
       //    {
       //        if (ViewState["ShowRestoreButton"] == null)
       //        {
       //            return true;
       //        }
       //        return (bool)ViewState["ShowRestoreButton"];
       //    }
       //    set
       //    {
       //        ViewState["ShowRestoreButton"] = value;
       //    }
       //}

       //[Category("工具栏")]
       //[Description("是否在工具栏显示数据视图按钮")]
       //public bool ShowDataViewButton
       //{
       //    get
       //    {
       //        if (ViewState["ShowDataViewButton"] == null)
       //        {
       //            return true;
       //        }
       //        return (bool)ViewState["ShowDataViewButton"];
       //    }
       //    set
       //    {
       //        ViewState["ShowDataViewButton"] = value;
       //    }
       //}

       //[Category("工具栏")]
       //[Description("数据视图是否只读")]
       //public bool DataViewReadOnly
       //{
       //    get
       //    {
       //        if (ViewState["DataViewReadOnly"] == null)
       //        {
       //            return true;
       //        }
       //        return (bool)ViewState["DataViewReadOnly"];
       //    }
       //    set
       //    {
       //        ViewState["DataViewReadOnly"] = value;
       //    }
       //}


       //[Category("工具栏")]
       //[Description("是否显示动态类型切换按钮")]
       //public bool ShowMagicTypeButton
       //{
       //    get
       //    {
       //        if (ViewState["ShowMagicTypeButton"] == null)
       //        {
       //            return true;
       //        }
       //        return (bool)ViewState["ShowMagicTypeButton"];
       //    }
       //    set
       //    {
       //        ViewState["ShowMagicTypeButton"] = value;
       //    }
       //}


       //[Category("工具栏")]
       //[Description("可动态切换表的类型")]
       //public List<ChartType> MagicTypeList
       //{
       //    get
       //    {
       //        return (List<ChartType>)ViewState["MagicTypeList"];
       //    }
       //    set
       //    {
       //        ViewState["MagicTypeList"] = value;
       //    }
       //}


       //[Category("图例")]
       //[Description("图例数据")]
       //public string[] LegendData
       //{
       //    get
       //    {
       //        return (string[])ViewState["LegendData"];
       //    }
       //    set
       //    {
       //        ViewState["LegendData"] = value;
       //    }
       //}



       //[Category("图例")]
       //[Description("图例数据")]
       //public List<double> LegendData2
       //{
       //    get
       //    {
       //        return (List<double>)ViewState["LegendData2"];
       //    }
       //    set
       //    {
       //        ViewState["LegendData"] = value;
       //    }
       //}


       //[Description("是否启用拖拽重计算特性")]
       //public bool Calculable
       //{
       //    get
       //    {
       //        if (ViewState["Calculable"] == null)
       //        {
       //            return true;
       //        }
       //        return (bool)ViewState["Calculable"];
       //    }
       //    set
       //    {
       //        ViewState["Calculable"] = value;
       //    }
       //}



       //[Category("X轴")]
       //[Description("X轴数据")]
       //public List<string> xAxisData
       //{
       //    get
       //    {
       //        return (List<string>)ViewState["xAxisData"];
       //    }
       //    set
       //    {
       //        ViewState["xAxisData"] = value;
       //    }
       //}


       //[Category("Y轴")]
       //[Description("Y轴间隔名称显示格式，例：{value} °C")]
       //public string yAxisLabelFormatter
       //{
       //    get
       //    {
       //        return (string)ViewState["yAxisLabelFormatter"];
       //    }
       //    set
       //    {
       //        ViewState["yAxisLabelFormatter"] = value;
       //    }
        //}
        #endregion



        /// <summary>
        /// 标题
        /// </summary>
        [Description("标题")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public Title.Title Title
        {
            get
            {
                if (ViewState["Title"] == null)
                {
                    ViewState["Title"] = new Title.Title();
                }
                return (Title.Title)ViewState["Title"];
            }
        }

        //隐藏父类同名属性
        [Browsable(false)]
        private string ToolTip { get; set; }

        /// <summary>
        /// 提示框，鼠标悬浮交互时的信息提示
        /// </summary>
        [Description("提示框，鼠标悬浮交互时的信息提示")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public  Tooltip.Tooltip Tooltip
        {
            get
            {
                if (ViewState["Tooltip"] == null)
                {
                    ViewState["Tooltip"] = new Tooltip.Tooltip();
                }
                return (Tooltip.Tooltip)ViewState["Tooltip"];
            }
        }

        /// <summary>
        /// 图例
        /// </summary>
        [Description("图例")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public Legend.Legend Legend
        {
            get
            {
                if (ViewState["Legend"] == null)
                {
                    ViewState["Legend"] = new Legend.Legend();
                }
                return (Legend.Legend)ViewState["Legend"];
            }
        }

        /// <summary>
        /// 工具栏
        /// </summary>
        [Description("工具栏")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Toolbox Toolbox
        {
            get
            {
                if (ViewState["Toolbox"] == null)
                {
                    ViewState["Toolbox"] = new Toolbox();
                }
                return (Toolbox)ViewState["Toolbox"];
            }
        }

        /// <summary>
        /// 是否启用拖拽重计算特性，默认关闭
        /// </summary>
        [Description("是否启用拖拽重计算特性，默认关闭")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public bool Calculable
        {
            get
            {
                if (ViewState["Calculable"] == null)
                {
                    ViewState["Calculable"] = false;
                }
                return (bool)ViewState["Calculable"];
            }
            set
            {
                ViewState["Calculable"] = value;
            }
        }

        /// <summary>
        /// X轴
        /// </summary>
        [Description("X轴")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<BaseAxisItem> xAxis
        {
            get
            {
                if (ViewState["xAxis"] == null)
                {
                    ViewState["xAxis"] = new List<BaseAxisItem>();
                }
                return (List<BaseAxisItem>)ViewState["xAxis"];
            }
        }

        /// <summary>
        /// Y轴
        /// </summary>
        [Description("Y轴")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<BaseAxisItem> yAxis
        {
            get
            {
                if (ViewState["yAxis"] == null)
                {
                    ViewState["yAxis"] = new List<BaseAxisItem>();
                }
                return (List<BaseAxisItem>)ViewState["yAxis"];
            }
        }


        /// <summary>
        /// 系列
        /// </summary>
       [Description("系列")]
       [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
       public List<SeriesItem> Series
       {
           get
           {
               if (ViewState["Series"] == null)
               {
                   ViewState["Series"] = new List<SeriesItem>();
               }
               return (List<SeriesItem>)ViewState["Series"];
           }
       }


       private Option _Option = new Option();
       [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
       public Option Option
       {
           get {
               return _Option;
           }
       }

       public EChart AddSeries(string name, ChartType type, IEnumerable data)
        {
           SeriesItem item = new SeriesItem();
           item.name = name;
           item.type = type;
           List<double> valueList=new List<double>();
           foreach( var valueItem in data )
           {
               double value;
               if (valueItem is string)
               {
                   value = Convert.ToDouble(valueItem);
               }
               else {
                   value = (double)valueItem;
               }
               valueList.Add(value);
           }
           item.data = valueList;
           Series.Add(item);
           return this;
        }

        
       public EChart AddxAxis(string name,string [] data)
       {
           return this;
       }


        protected override void RenderContents(HtmlTextWriter output)
        {
            
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            writer.AddStyleAttribute(HtmlTextWriterStyle.Width,this.Width.ToString());
            writer.AddStyleAttribute(HtmlTextWriterStyle.Height,this.Height.ToString());
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            #region 旧代码
            /*
            Option option = new Option();
            //title
            option.title=new Title.Title();
            option.title.text = this.Title;
            option.title.subtext = this.SubTitle;
            //legend
            option.legend=new Legend.Legend();
            option.legend.data = this.LegendData;
            //toolbox
            option.toolbox = new Toolbox();
            option.toolbox.show = this.ShowToolbox.ToString().ToLower();
            option.toolbox.feature = new Feature();
            option.toolbox.feature.dataView = new DataView();
            option.toolbox.feature.dataView.show = this.ShowDataViewButton;
            option.toolbox.feature.dataView.readOnly = this.DataViewReadOnly;
            option.toolbox.feature.magicType = new MagicType();
            option.toolbox.feature.magicType.show = this.ShowMagicTypeButton;
            option.toolbox.feature.magicType.type = this.MagicTypeList;
            option.toolbox.feature.restore = new Restore();
            option.toolbox.feature.restore.show = this.ShowRestoreButton;
            option.toolbox.feature.saveAsImage = new SaveAsImage();
            option.toolbox.feature.saveAsImage.show = this.ShowSaveAsImageButton;
            //calculable
            option.calculable = this.Calculable;
            //xAxis
            option.xAxis = new List<XAxisItem>();
            XAxisItem xAxisItem = new XAxisItem();
            xAxisItem.type = AxisType.Category;
            xAxisItem.boundaryGap = "false";
            xAxisItem.data = this.xAxisData;
            option.xAxis.Add(xAxisItem);
            //yAxis
            option.yAxis = new List<YAxisItem>();
            YAxisItem yAxisItem = new YAxisItem();
            yAxisItem.type = "value";
            yAxisItem.axisLabel = new AxisLabel();
            yAxisItem.axisLabel.formatter = this.yAxisLabelFormatter;
            //series
            option.title.



            var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore ,};
            jsonSetting.Converters.Add(new BoolConvert("true,false"));
            string script = string.Format(@"<script>
                                            // window.onload=function(){{
                                                InitEchart('{0}',{1});
                                            // }}
                                           </script>", this.ClientID, JsonConvert.SerializeObject(option, Formatting.Indented, jsonSetting));
            writer.Write(script);
             */
            #endregion

            Option option = new Option();
            option.backgroundColor = BackColor;
            //option.title = this.Title;
            option.Tooltip = this.Tooltip;
            option.legend = this.Legend;
            option.toolbox = this.Toolbox;
            option.calculable = this.Calculable;
            option.xAxis = this.xAxis;
            option.yAxis = this.yAxis;
            option.series = this.Series;
            Newtonsoft.Json.JsonSerializerSettings jsonSetting = new Newtonsoft.Json.JsonSerializerSettings();
            JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
            {
                //首字母小写
                jsonSetting.ContractResolver = new LowerCaseContractResolver();

                //日期类型默认格式化处理
                //setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                //setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";

                //空值处理
                jsonSetting.NullValueHandling = NullValueHandling.Ignore;

                //Bool类型转换为小写
                jsonSetting.Converters.Add(new BoolConverter("true,false"));

                //枚举类型的Json转换
                jsonSetting.Converters.Add(new StringEnumConverter());

                //List<ChartType> 类型的json转换
                jsonSetting.Converters.Add(new EnumListConverter<ChartType>());

                jsonSetting.Converters.Add(new ColorConverter());

                return jsonSetting;
            });
            string script = string.Format(@"<script>
                                                InitEchart('{0}',{1});
                                           </script>", this.ClientID, JsonConvert.SerializeObject(option, Formatting.Indented, jsonSetting));
            writer.Write(script);

        }

        protected override void OnLoad(EventArgs e)
        {        
            this.Page.ClientScript.RegisterClientScriptResource(typeof(EChart), "ECharts.js.echarts-all.js");

            string script = @"function InitEchart(id,option){
                                       var _EChart = echarts.init(document.getElementById(id));
                                       _EChart.setOption(option);
                                   }";
            
            Page.ClientScript.RegisterClientScriptBlock(GetType(),"InitEChart",script,true);
            base.OnLoad(e);
        }

      
    }
}
